package com.asiainfo.dacp.datastash.broker.flow.core.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.asiainfo.dacp.datastash.broker.common.enums.UnitStateEnum;
import com.asiainfo.dacp.datastash.broker.core.enums.UnitTaskStateEnum;
import com.asiainfo.dacp.datastash.broker.core.vo.StashUnitTask;
import com.asiainfo.dacp.datastash.broker.flow.core.domain.Flow;
import com.asiainfo.dacp.datastash.broker.flow.core.repo.TaskStateRepository;
import com.asiainfo.dacp.datastash.broker.flow.core.repo.UnitStateRepository;
import com.asiainfo.dacp.datastash.broker.redis.service.RedisFlowService;

@Service
public class FlowStateChangeService {
	private static Logger LOG = LoggerFactory.getLogger(FlowStateChangeService.class);

	@Autowired
	private UnitStateRepository unitStateRepo;

	@Autowired
	private TaskStateRepository taskStateRepo;

	public void flowInit(Flow flow) {
		flow.setRemark("作业初始化.");
		flow.setUnitState(UnitStateEnum.INIT);
		unitStateRepo.createOrUpdate(flow);
	}

	public void dependOK(Flow flow) {
		flow.setRemark("依赖判断通过，执行任务分配.");
		flow.setUnitState(UnitStateEnum.RUNNABLE);
		unitStateRepo.createOrUpdate(flow);
	}

	public void dependNotOK(Flow flow) {
		flow.setRemark("依赖判断未通过，等待下次判断.");
		flow.setUnitState(UnitStateEnum.BLOCKED_RELAY);
		unitStateRepo.createOrUpdate(flow);
	}

	public void compileOK(Flow flow) {
		flow.setRemark(String.format("编译通过，任务数为 %d. 任务开始运行.", flow.getTaskCnt()));
		flow.setUnitState(UnitStateEnum.RUNNING_COMPILE);
		unitStateRepo.createOrUpdate(flow);
		taskStateRepo.create(flow);
	}

	public void running(Flow flow) {
		flow.setRemark("任务正在运行.");
		flow.setUnitState(UnitStateEnum.RUNNING);
		unitStateRepo.createOrUpdate(flow);
	}

	public void compileNotOK(Flow flow) {
		flow.setRemark("编译未通过，作业失败.");
		flow.setUnitState(UnitStateEnum.FAIL);
		unitStateRepo.createOrUpdate(flow);
	}

	public void LineNotOK(Flow flow) {
		flow.setRemark("线性规划异常，作业失败.");
		flow.setUnitState(UnitStateEnum.FAIL);
		unitStateRepo.createOrUpdate(flow);
	}

	public void LineOK(Flow flow) {
		flow.setRemark(String.format("正在运行，满足运行条件的任务::%d", flow.getTaskRunnableCnt()));
		flow.setUnitState(UnitStateEnum.RUNNING);
		unitStateRepo.createOrUpdate(flow);
		taskStateRepo.update(flow);
	}

	public void taskRunning(StashUnitTask task) {
		task.setTaskState(UnitTaskStateEnum.RUNNING);
		taskStateRepo.update(task);
	}
}
